<?php

namespace App\Services;

use App\Core\Config;

class ThemeManager
{
    private static $instance = null;
    private $currentTheme;
    private $availableThemes = [];
    private $themeConfig = [];

    private function __construct()
    {
        $this->loadAvailableThemes();
        $this->currentTheme = $this->getConfiguredTheme();
    }

    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 获取当前主题
     */
    public function getCurrentTheme()
    {
        return $this->currentTheme;
    }

    /**
     * 设置当前主题
     */
    public function setCurrentTheme($theme)
    {
        if (!in_array($theme, $this->availableThemes)) {
            throw new \Exception("主题 '{$theme}' 不存在");
        }

        $this->currentTheme = $theme;

        // 更新设置
        try {
            $settings = SettingsService::getInstance();
            if (!SettingsService::set('current_theme', $theme)) {
                throw new \Exception("保存主题设置失败");
            }
        } catch (\Exception $e) {
            throw new \Exception("保存主题设置失败: " . $e->getMessage());
        }

        return true;
    }

    /**
     * 获取所有可用主题
     */
    public function getAvailableThemes()
    {
        return $this->availableThemes;
    }

    /**
     * 获取主题配置
     */
    public function getThemeConfig($theme = null)
    {
        $theme = $theme ?: $this->currentTheme;
        return $this->themeConfig[$theme] ?? [];
    }

    /**
     * 获取主题模板路径
     */
    public function getThemePath($template)
    {
        $templatesDir = defined('TEMPLATES_DIR') ? TEMPLATES_DIR : (APP_ROOT . '/templates');

        // 先检查当前主题是否有此模板
        $themePath = "themes/{$this->currentTheme}/{$template}.php";
        if (file_exists($templatesDir . "/{$themePath}")) {
            return $themePath;
        }

        // 如果当前主题没有，则使用默认主题
        $defaultPath = "themes/default/{$template}.php";
        if (file_exists($templatesDir . "/{$defaultPath}")) {
            return $defaultPath;
        }

        // 如果默认主题也没有，则使用原始模板
        return "{$template}.php";
    }

    /**
     * 加载所有可用主题
     */
    private function loadAvailableThemes()
    {
        $templatesDir = defined('TEMPLATES_DIR') ? TEMPLATES_DIR : (APP_ROOT . '/templates');
        $themesDir = $templatesDir . '/themes';
        if (!is_dir($themesDir)) {
            mkdir($themesDir, 0755, true);
        }

        $this->availableThemes = [];
        $this->themeConfig = [];

        // 扫描主题目录
        $dirs = scandir($themesDir);
        foreach ($dirs as $dir) {
            if ($dir === '.' || $dir === '..') {
                continue;
            }

            if (is_dir($themesDir . '/' . $dir)) {
                $this->availableThemes[] = $dir;

                // 加载主题配置
                $configFile = $themesDir . '/' . $dir . '/theme.json';
                if (file_exists($configFile)) {
                    $this->themeConfig[$dir] = json_decode(file_get_contents($configFile), true);
                } else {
                    // 创建默认配置
                    $this->themeConfig[$dir] = [
                        'name' => ucfirst($dir),
                        'description' => ucfirst($dir) . ' 主题',
                        'version' => '1.0.0',
                        'author' => 'MyCMS',
                        'screenshot' => '/assets/images/themes/' . $dir . '.jpg'
                    ];
                }
            }
        }

        // 确保至少有默认主题
        if (!in_array('default', $this->availableThemes)) {
            $this->availableThemes[] = 'default';
            $this->themeConfig['default'] = [
                'name' => '默认主题',
                'description' => '系统默认主题',
                'version' => '1.0.0',
                'author' => 'MyCMS',
                'screenshot' => '/assets/images/themes/default.jpg'
            ];
        }
    }

    /**
     * 获取配置中的主题
     */
    private function getConfiguredTheme()
    {
        try {
            $settings = SettingsService::getInstance();
            $theme = $settings->get('current_theme', 'default');
        } catch (\Exception $e) {
            // 如果获取设置失败，使用默认主题
            $theme = 'default';
        }

        // 确保主题存在
        if (!in_array($theme, $this->availableThemes)) {
            $theme = 'default';
        }

        return $theme;
    }
}
